import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/src/entities/format/service_and_product_entity.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';

mixin FormItemAmountMixin<T> on BaseProvider<T> {
  List<ServiceAndProductEntity> serviceAndProductList = [];

  List<ServiceAndProductEntity> availableItems = [];

  bool isCredit = false;

  int get billInvoiceId;

  double get subTotal {
    double total = 0.0;
    serviceAndProductList.forEach((element) {
      total += double.parse(element.discountedAmount.toString(), (e) => 0.0);
    });
    return total;
  }

  double get discount => 0.0;

  double get creditUsed => 0.0;

  double get totalDiscount {
    return ((total ?? 0.0) - (creditUsed ?? 0.0) - (discount ?? 0.0))
        .clamp(0.0, double.infinity);
  }

  double get total {
    return subTotal + gst;
  }

  double get gst {
    double total = 0.0;
    serviceAndProductList.forEach((element) {
      if (element.isInclusive == false) {
        total += double.parse(element.discountedAmount.toString(), (e) => 0.0) *
            element.rate /
            100;
      }
    });
    return total;
  }

  double get includesGST {
    double total = 0.0;
    serviceAndProductList.forEach((element) {
      if (element.isInclusive) {
        total += calInclusiveGST(element.discountedAmount, element.rate / 100);
      }
    });
    return total;
  }

  double calInclusiveGST(num amount, num gstRate) {
    if (amount == 0) return 0.0;
    return amount - (amount / (1 + gstRate ?? 0)).toDouble();
  }

  void unFocus();

  void onAddItem() async {
    unFocus();
    final result =
        await Routes.navigateTo(RouterGenProviders.selectItemPage, params: {
      'billInvoiceId': billInvoiceId,
      'isCredit': isCredit,
    });
    if (result != null) {
      serviceAndProductList.add(result);
      update();
    }
  }

  void onSelectItem(ServiceAndProductEntity value) async {
    final result =
        await Routes.navigateTo(RouterGenProviders.itemAmountPage, params: {
      'item': value,
      'isCredit': isCredit,
      'isEdit': true,
    });
    if (result is ServiceAndProductEntity) {
      print(result.product.toJson());
      if (value.product != null) {
        serviceAndProductList
            .firstWhere((element) => element == value)
            .fromJson(result.toJson());
      }
      if (value.services != null) {
        serviceAndProductList
            .firstWhere((element) => element == value)
            .fromJson(result.toJson());
      }
      value.number = result.number;
    } else if (result != null && result['delete'] != null) {
      bool delete = result['delete'];
      if (delete == true) {
        serviceAndProductList.remove(value);
      }
    }
    update();
  }
}
